import React from 'react'
import { Tabs } from 'antd'
import { CloseOutlined } from '@ant-design/icons'
import { useDrag, useDrop } from 'react-dnd'

const { TabPane } = Tabs

type Tab = {
  id: string
  title: string
  content: string
}

type TabBarProps = {
  tabs: Tab[]
  setTabs: (tabs: Tab[]) => void
  activeTab: string
  setActiveTab: (id: string) => void
  removeTab: (id: string) => void
}

const TabBar: React.FC<TabBarProps> = ({ tabs, setTabs, activeTab, setActiveTab, removeTab }) => {
  const moveTab = (dragIndex: number, hoverIndex: number) => {
    const newTabs = [...tabs]
    const [movedTab] = newTabs.splice(dragIndex, 1)
    newTabs.splice(hoverIndex, 0, movedTab)
    setTabs(newTabs)
  }

  return (
    <Tabs
      activeKey={activeTab}
      onChange={setActiveTab}
      type="editable-card"
      hideAdd
      onEdit={(targetKey, action) => action === 'remove' && removeTab(targetKey.toString())}
    >
      {tabs.map((tab, index) => (
        <TabPane
          key={tab.id}
          tab={<DraggableTab tab={tab} index={index} moveTab={moveTab} removeTab={removeTab} />}
        />
      ))}
    </Tabs>
  )
}

// 处理可拖拽的 Tab
const DraggableTab: React.FC<{
  tab: Tab
  index: number
  moveTab: (from: number, to: number) => void
  removeTab: (id: string) => void
}> = ({ tab, index, moveTab, removeTab }) => {
  const ref = React.useRef<HTMLDivElement>(null)
  const [{ isDragging }, drag] = useDrag({
    type: 'TAB',
    item: { index },
    collect: (monitor) => ({
      isDragging: monitor.isDragging()
    })
  })

  const [, drop] = useDrop({
    accept: 'TAB',
    hover: (item: { index: number }) => {
      if (item.index !== index) {
        moveTab(item.index, index)
        item.index = index
      }
    }
  })

  drag(drop(ref))

  return (
    <div
      ref={ref}
      style={{
        opacity: isDragging ? 0.5 : 1,
        cursor: 'move',
        display: 'flex',
        alignItems: 'center'
      }}
    >
      {tab.title}
      <CloseOutlined onClick={() => removeTab(tab.id)} style={{ marginLeft: 8 }} />
    </div>
  )
}

export default TabBar
